package com.hypo.filter;

import com.hypo.until.CurrentHolder;
import com.hypo.until.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

/**
 * 默认按照名字自然排序谁在前面谁先执行
 * 自定义排序：
 * 1）将过滤器交给SpringIOC容器管理
 * 2）使用@Order注解设置排序，值越小，越靠前
 */
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1、为了获取客户端数据，以及响应客户端数据，将ServletRequest转成HttpServletRequest，将ServletResponse转成HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.获取请求路径
        String url = request.getRequestURL().toString();
        //3.判断是否需要拦截，请求路径中包含login不需要拦截
        if (url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //4.获取请求头令牌
        String token = request.getHeader("token");
        //5.令牌校验（令牌为空，或者令牌不通过，都要拦截）
        if (ObjectUtils.isEmpty(token) || JwtUtils.parseJWT(token) == null) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        //解析jwt获取用户信息
        Claims claims = JwtUtils.parseJWT(token);
        Integer id = Integer.parseInt(claims.get("id").toString());
        CurrentHolder.setCurrentId(id);

        //6.校验通过，放行请求
        filterChain.doFilter(servletRequest, servletResponse);
        //移除,清除ThreadLocal的数据（如果不清除，会导致内存泄漏）
        CurrentHolder.remove();
    }
}
